package cn.bqjr.eily.web.utils;

import cn.bqjr.eily.core.log.LogAopEntity;
import cn.bqjr.eily.core.log.LogAopUtils;
import javassist.NotFoundException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志AOP工具类
 */
public class WebLogAopUtils extends LogAopUtils {

    private static final List<Class> controllerClassList = Arrays.asList(
            RequestMapping.class, GetMapping.class, PostMapping.class, DeleteMapping.class, PutMapping.class);

    /**
     * 获取请求信息
     *
     * @param entity
     * @return
     * @throws NotFoundException
     */
    public static Map<String, Object> getHttpRequestInfo(LogAopEntity entity) throws NotFoundException {
        Map<String, Object> reqMap = new HashMap<>();
        if (entity.isHttpRequest()) {
            HttpServletRequest request = entity.getRequest();
            reqMap.put("reqURL", request.getRequestURL().toString());
            reqMap.put("reqMethod", request.getMethod());
            reqMap.put("ipAddr", WebUtils.getIpAddr(request));
        }
        reqMap.putAll(getRequestInfo(entity));
        return reqMap;
    }

    /**
     * 是否包含controller mapping注解
     *
     * @param method
     * @return
     */
    public static boolean isControllerAnnoPresent(Method method) {
        return controllerClassList.stream().anyMatch(cls -> method.isAnnotationPresent(cls));
    }
}
